import {BrowserWindow,ipcMain,WebContentsView} from "electron";
import {WebviewConfig} from "@type/webview.ts";
export class CusIpcMain {
    private win:BrowserWindow
    constructor(win:BrowserWindow) {
        this.win=win
        this.init()
    }
    init(){
        console.log("初始化主进程窗体")
        this.open_windows();
        this.mainWindowEvents()
    }
    // 向渲染进程发送消息
    sendIpcRender(){
        this.win.webContents.send("send-render","I am main process!")
    }
    open_windows(){
        listen("create-new-webview",(args:WebviewConfig)=>{
            console.log(args)
            const {x,y,width,height}=args
            const webView = new WebContentsView();
            this.win.contentView.addChildView(webView)
            webView.webContents.loadURL(args.url)
            webView.setBounds({x,y,width,height})
        })
    }
    mainWindowEvents(){
        this.win.webContents.openDevTools()
        ipcMain.on("win_max",()=>{
            if (this.win.isMaximized()) {
                this.win.unmaximize(); // 如果窗口已最大化，则恢复窗口
            } else {
                this.win.maximize(); // 否则，最大化窗口
            }
        })
        ipcMain.on("win_close",()=>{
            this.win.close();
        })
        ipcMain.on("win_min",()=>{
            this.win.minimize();
        })
    }
}
export const listen = (cmd:string,cb) => {
    ipcMain.on(cmd,(event, args)=>{
        console.log("渲染进程发送消息了")
        cb(args)
    })
}
export const listenHandle=(cmd:string)=>{
    ipcMain.handle(cmd,(event, args)=>{
        return args
    })
}
